﻿/*-----------------------------------------------------------------------
 * <copyright file="DataExport.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>zhangjun</author>
 * <summary>       
 *              DataGrid 数据导出到 DSV 
 *              
 *          07/30/2010 修改 千分位分割符用TAB替换问题
 *          08/10/2010 ExportDataGrid方法中添加用List<string[]>当数据源导出
 *          
 *</summary>
 *-----------------------------------------------------------------------
 */
namespace Orid.Management.Statistics.OperatorUnitMangement.Common.Export
{
    using System;
    using System.Windows.Controls;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    /// Class of DataExport
    /// </summary>
    public class DataExport
    {  
       /// <summary> 
        /// 导出DataGrid 数据到 DSV 
       /// </summary> 
       /// <param name="withHeaders">是否需要表头 withHeaders</param> 
        /// <param name="grid">DataGrid的表头 grid</param> 
        /// <param name="gridToDate">DataGrid的内容 grid</param>
        /// <param name="listToDate">List的内容 listToDate</param>
       /// <returns>Excel 内容字符串 </returns> 
        public static string ExportDataGrid(bool withHeaders, DataGrid grid, DataGrid gridToDate, List<string[]> listToDate)
       {
           string colPath;
           System.Reflection.PropertyInfo propInfo;
           System.Windows.Data.Binding binding;
           System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
           //if (grid.ItemsSource == null)
           //{
           //    return "";
           //}


           List<string> headers = new List<string>();

           foreach (DataGridColumn col in grid.Columns)
           {
               if (col is DataGridTextColumn)
               {
                   if (col.Header != null)
                   {
                       string headerStr = FormatCSVField(col.Header.ToString());

                       //修改DataGrid表头 ：2010-01-01  月
                       if (gridToDate == null && listToDate != null)
                       {
                           Regex regex = new Regex("\\s+ ");
                           headerStr = regex.Replace(headerStr, " "); 
                       }

                       headers.Add(headerStr);
                   }
                   else
                   {
                       headers.Add(string.Empty);
                   }
               }
           }

           //由 逗号 换成 ^ ,--07/30/2010--Edit
           strBuilder.Append(String.Join("^", headers.ToArray())).Append(Environment.NewLine);


            // 用DATAGRID 填充
           if (gridToDate != null && gridToDate.ItemsSource != null)
           {
               
               foreach (object data in gridToDate.ItemsSource)
               {
                   List<string> csvRow = new List<string>();
                   foreach (DataGridColumn col in grid.Columns)
                   {
                       if (col is DataGridTextColumn)
                       {
                           binding = (col as DataGridBoundColumn).Binding;
                           colPath = binding.Path.Path;
                           propInfo = data.GetType().GetProperty(colPath);
                           if (propInfo != null)
                           {
                               csvRow.Add(FormatCSVField(propInfo.GetValue(data, null).ToString()));
                           }
                       }
                   }
                   //由 逗号 换成 ^ ,--07/30/2010--EIDT
                   strBuilder.Append(String.Join("^", csvRow.ToArray())).Append(Environment.NewLine);
               }
           }
           else // 用List<string[]>  填充
           {
               if (listToDate == null || listToDate.Count <= 0) 
               {
                   throw new Exception("导出的数据源为空！");
               }

               // 所有行
               foreach (string[] col in listToDate)
               {
                   List<string> csvRow = new List<string>();
                   if (col != null) 
                   {
                       //一行的各个列
                       foreach (string str in col)
                       {
                           csvRow.Add(FormatCSVField(str.ToString()));
                       }
                   }
                   //由各个列组成一行
                   strBuilder.Append(String.Join("^", csvRow.ToArray())).Append(Environment.NewLine);
               }
           }
           return strBuilder.ToString();
       }

       /// <summary>
       /// CSV 格式化 FormatCSVField表头
       /// </summary>
       /// <param name="data">数据 type string data</param>
       /// <returns>格式化数据 static string</returns>
       private static string FormatCSVField(string data)
       {
           return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
       }

    }
}
